package utils;

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;

/**
 * Unlike the one from Java, this Canvas resizes with the parent.
 *
 * <p>Hack based on code from:
 * http://dlemmermann.wordpress.com/2014/04/10/javafx-tip-1-resizable-canvas/</p>
 *
 * @author Ricardo Cruz {@literal <ricardo.pdm.cruz@gmail.com>}
 * @since  2014-11-13
 */
public abstract class ResizableCanvas extends StackPane
{
	private MyResizableCanvas canvas;

	public ResizableCanvas() {
		super();
		canvas = new MyResizableCanvas();
		getChildren().add(canvas);

		canvas.widthProperty().bind(widthProperty());
		canvas.heightProperty().bind(heightProperty());

		canvas.widthProperty().addListener(ev -> repaint());
		canvas.heightProperty().addListener(ev -> repaint());
	}

	protected abstract void draw(GraphicsContext gc, double width, double height);

	public void repaint() {
		draw(canvas.getGraphicsContext2D(), canvas.getWidth(), canvas.getHeight());
	}

	private static class MyResizableCanvas extends Canvas {
		public boolean isResizable() { return true; }
		public double prefWidth(double height) { return getWidth(); }
		public double prefHeight(double width) { return getHeight(); }
	}
}
